<?php

namespace app\zyhsapi\model;

use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsAstrBindUser extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_astr_bind_user';

    protected $cacheModel = 'zyhs.astr_bind_user';

    public function saveData($data)
    {
        try
        {
            $id = $this->insertGetId($data);
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->rmCache();
        }
        catch (\Exception $e)
        {
            Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
        return $id;
    }

    public function updateData($uid, $data)
    {
        try
        {
            $this->where('uid', $uid)->update($data);
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->rmCache();
        }
        catch (\Exception $e)
        {
            Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }

    protected static $astrBindUserData = null;

    /**
     * 获取占星师绑定 用户信息
     * @return array   ['uid' => 'astr_id']
     * @throws \Exception
     */
    public function getAstrBindUserData()
    {
        if (!is_null(self::$astrBindUserData))
        {
            return self::$astrBindUserData;
        }

        $data = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->getDataAndSet(function ()
        {
            try
            {
                $data = $this->where(['status' => 1])->column('astr_id', 'uid');
                if ($data)
                {
                    return $data;
                } else
                {
                    return [0 => 0];
                }
            }
            catch (\Exception $e)
            {
                return '';
            }
        });
        unset($data[0]);
        foreach ($data as $uid => $astrId)
        {
            $data[$uid] = (int)$astrId;
        }
        self::$astrBindUserData = $data;

        return $data;
    }
}
